package com.gourd.common.log.service.impl;

import com.gourd.common.rbac.vo.JwtUser;
import com.gourd.common.utils.JwtUtil;
import com.gourd.common.log.dao.LogDao;
import com.gourd.common.log.entity.Log;
import com.gourd.common.log.service.LogService;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author gourd
 * @date 2018-11-24
 */
@Service
@Transactional(rollbackFor = Exception.class)
@RefreshScope
public class LogServiceImpl implements LogService {

    @Autowired
    private LogDao logMapper;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public void save(ProceedingJoinPoint joinPoint,String jwtToken,String ip,Log log){
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        com.gourd.common.annotation.Log aopLog = method.getAnnotation(com.gourd.common.annotation.Log.class);
        // 描述
        if (log != null) {
            log.setDescription(aopLog.value());
        }
        // 方法路径
        String methodName = joinPoint.getTarget().getClass().getName()+"."+signature.getName()+"()";
        StringBuilder params = new StringBuilder("{");
        //参数值
        Object[] argValues = joinPoint.getArgs();
        //参数名称
        String[] argNames = ((MethodSignature)joinPoint.getSignature()).getParameterNames();
        if(argValues != null){
            for (int i = 0; i < argValues.length; i++) {
                params.append(" ");
                params.append(argNames[i]);
                params.append(argValues[i]);
            }
        }
        params.append(" }");
        // 获取IP地址
        log.setRequestIp(ip);
        if(StringUtils.isNotEmpty(jwtToken)){
            // 获取当前用户
            JwtUser currentUser = jwtUtil.getUserFromToken(jwtToken);
            if(currentUser != null){
                log.setMethod(methodName);
                log.setUserId(currentUser.getId());
                log.setUserName(currentUser.getName());
                log.setParams(params.toString());
                log.setCreatedBy(currentUser.getId());
                log.setCreatedTime(new Date());
                log.setDeleted(false);
                log.setVersion(1L);
                // 保存访问日志
                logMapper.insert(log);
            }
        }
    }
}
